package lagou.mode3.mode4;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.util.List;

public class ServerThread extends Thread{
    private Socket accept;
    private List<Socket> acceptList;
    public ServerThread(Socket accept, List<Socket> acceptList){
        this.accept=accept;
        this.acceptList=acceptList;
    }
    @Override
    public void run(){
        BufferedReader br = null;
        BufferedOutputStream bo2=null;
        try {
            BufferedInputStream bi = new BufferedInputStream(accept.getInputStream());
            br = new BufferedReader(new InputStreamReader(accept.getInputStream()));
            while (true) {
                String str1=br.readLine();
                System.out.println("客户端"+accept.getInetAddress()+"发来的信息为："+str1);
                if("即将发送文件，请注意接收".equals(str1)){
                    String name=br.readLine();
                    String path="e:/"+name;
                    FileOutputStream fileOutputStream = new FileOutputStream(path);
                    bo2=new BufferedOutputStream(fileOutputStream);
                    byte[] bArr=new byte[1024];
                    int res=0;
                    System.out.println("正在下载文件...");
                    while ((res=bi.read(bArr))!=-1){
                        bo2.write(bArr,0,res);
                    }
                    System.out.println("文件下载完成");
                    break;
                }
                for(Socket ac:acceptList){
                    PrintStream pps = new PrintStream(ac.getOutputStream());
                    //将“发送方地址+消息内容”发给当前在线的所有客户端
                    pps.println(accept.getInetAddress()+": "+str1);
                }
                System.out.println("成功转发给所有在线客户端");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(null !=br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
